/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-maintain
*
* @File name : MaintainService.java
*
* @Author : Administrator
*
* @Date : 2017年3月8日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年3月8日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.maintain.service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import org.apache.log4j.Logger;
import org.marketing.common.constants.CodeConstant;
import org.marketing.common.constants.CommonConstant;
import org.marketing.common.dms.dto.IfMessage;
import org.marketing.common.dms.dto.ResultMessage;
import org.marketing.common.dms.http.HttpCommonUtil;
import org.marketing.common.dto.MessageDto;
import org.marketing.common.dto.SendTicket;
import org.marketing.common.dto.freeTime.FreeTimeDto;
import org.marketing.common.dto.maintain.CarModelDto;
import org.marketing.common.dto.maintain.MaintainDealerDto;
import org.marketing.common.dto.maintain.MaintainDto;
import org.marketing.common.dto.maintain.MaintainFrecordDto;
import org.marketing.common.dto.maintenanceorder.MaintenanceDto;
import org.marketing.common.event.BizEvent;
import org.marketing.common.event.EventEvaluationDTO;
import org.marketing.common.event.EventInsuranceExpireDTO;
import org.marketing.common.event.EventMaintainChangedDTO;
import org.marketing.common.event.EventMaintainExpireDTO;
import org.marketing.common.event.EventMaintainSendMessageDto;
import org.marketing.common.event.EventRepairAppointmentArrivedDTO;
import org.marketing.common.event.enums.EventConstant;
import org.marketing.common.event.enums.EventConstant.EventBizStep;
import org.marketing.common.event.enums.EventConstant.EventBizType;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.DateUtil;
import org.marketing.common.util.MD5Util;
import org.marketing.common.util.MapConverUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import com.alibaba.fastjson.JSON;
import com.ibm.icu.text.SimpleDateFormat;
import com.ibm.icu.util.Calendar;
import com.yonyou.gmmc.common.service.BaseService;
import com.yonyou.gmmc.service.maintain.constant.MaintainConstant;
import com.yonyou.gmmc.service.maintain.dao.TmCarInfoMapper;
import com.yonyou.gmmc.service.maintain.dao.TtMaintenanceRecordMapper;
import com.yonyou.gmmc.service.maintain.dao.TtReservationMapper;
import com.yonyou.gmmc.service.maintain.dto.InsuranceDto;
import com.yonyou.gmmc.service.maintain.dto.InsuranceExpireDto;
import com.yonyou.gmmc.service.maintain.dto.MaintainExpireDto;
import com.yonyou.gmmc.service.maintain.dto.WorkStationsDto;
import com.yonyou.gmmc.service.maintain.model.ApplyConfirm;
import com.yonyou.gmmc.service.maintain.model.MaintainInfo;
import com.yonyou.gmmc.service.maintain.model.TmCarInfo;
import com.yonyou.gmmc.service.maintain.model.TtReservation;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

/**
 * @author Administrator
 * @date 2017年3月8日
 */
@Service("maintainmService")
public class MaintainService extends BaseService {

	private Logger logger = Logger.getLogger(MaintainService.class);

	@Autowired
	private TtMaintenanceRecordMapper ttMaintenanceRecordMapper;

	@Autowired
	private TtReservationMapper ttReservationMapper;

	@Autowired
	private BaseService eventService;

	@Autowired
	private TmCarInfoMapper tmCarInfoMapper;

	@Value("${INSURANCE-URL}")
	private String insuranceUrl;
	@Value("${MAINTAIN-URL}")
	private String maintainUrl;
	@Value("${INSURANCE_DATE}")
	private String insuranceDate;
	@Value("${DOMAIN_NAME}")
	private String domainName;
	@Value("${SMS-pass}")
	private String smsPass;
	@Value("${SMS-key}")
	private String smsKey;
	@Value("${SMS_CDKEY}")
	private String SMS_CDKEY;
	@Value("${SMS_PASS}")
	private String SMS_PASS;
	@Value("${SMS_BASEURL}")
	private String SMS_BASEURL;

	/**
	 * 取得空余时间-不包含工位信息，分时段的。每半小时为一个时段
	 * 
	 * @author WangHuicheng
	 * @date 2016年12月7日
	 * @param dealerCode
	 * @param bookDate
	 * @param bookingType
	 * @return
	 */
	public List<String> getFreeTimeNoWorkStation(String dealerCode) throws Exception {
		try {
			TimeZone tz = TimeZone.getTimeZone("Asia/Shanghai");
			TimeZone.setDefault(tz);
			this.logger.info(this.getClass().getName() + ":getFreeTimeNoWorkStation:begin");
			List<String> timeList = new ArrayList<>();
			List<FreeTimeDto> list = new ArrayList<>();
			list = ttMaintenanceRecordMapper.getFreeTime(dealerCode);

			if (list.size() == 0) {
				logger.info("未查到该店的空闲时间");
				FreeTimeDto e = new FreeTimeDto();
				e.setBeginTime("09");
				e.setEndTime("16");
				list.add(e);
			}
			for (FreeTimeDto freeTimeDto : list) {
				logger.info("开始时间：" + freeTimeDto.getBeginTime());
				logger.info("结束时间：" + freeTimeDto.getEndTime());
				Date date = DateUtil.dateFormat(freeTimeDto.getBeginTime() + ":00:00", "HH:mm:ss");
				Calendar beginTime = Calendar.getInstance();
				beginTime.setTime(date);
				// 30分钟为间隔
				Date dateEnd = DateUtil.dateFormat(freeTimeDto.getEndTime() + ":00:00", "HH:mm:ss");
				Calendar endTime = Calendar.getInstance();
				endTime.setTime(dateEnd);
				// 结束时间-30分钟
				endTime.add(Calendar.MINUTE, -30);
				// Properties props=System.getProperties();
				// Iterator iter=props.keySet().iterator();
				// while(iter.hasNext()){
				// String key=(String)iter.next();
				// logger.info(key+" = "+ props.get(key));
				// }
				timeList.add(String.format("%02d", beginTime.get(Calendar.HOUR_OF_DAY)) + ":"
						+ String.format("%02d", beginTime.get(Calendar.MINUTE)));
				while (!endTime.before(beginTime)) {// 让最后一个时间出现
					// 30分钟为间隔
					beginTime.add(Calendar.MINUTE, 30);
					timeList.add(String.format("%02d", beginTime.get(Calendar.HOUR_OF_DAY)) + ":"
							+ String.format("%02d", beginTime.get(Calendar.MINUTE)));
				}
			}
			for (int a = 0; a < timeList.size(); a++) {
				logger.info(timeList.get(a));
			}
			// 调用DCMS接口获取工位
			// List<Map<String, Object>> li = workStations(timeList, dealerCode,
			// time);

			return timeList;
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	/**
	 * 保存养修预约信息
	 * 
	 * @author WangHuicheng
	 * @date 2016年11月3日
	 * @param maintainDto
	 */
	public Map<String, Object> saveMaintain(@RequestBody MaintainDto maintainDto) {
		Map<String, Object> map = new HashMap<>();
		if (CheckUtil.NullOrEmpty(maintainDto.getVin())) {
			// 查询车辆信息
			List<MaintainDto> vinDto = ttMaintenanceRecordMapper
					.queryMaintainSel(Integer.valueOf(maintainDto.getUserId()));
			String vin = "";
			if (vinDto.size() == 0) {
				logger.info("暂未绑车");
			} else {
				vin = vinDto.get(0).getVin();
			}
			maintainDto.setVin(vin);
		}

		if (!maintainDto.getReseApplStartTime().after(new Date())) {
			map.put("errorCode", "0");
			map.put("errorMsg", "请选择晚于当前时间的预约时间！");
			return map;
		}

		// 预约次数的限制
		// 1.待确认和已确认的装
		// 2.预约到达的时间还没到
		// 3.同一辆车
		if (countCarReservations(maintainDto) > 0) {
			map.put("errorCode", "0");
			map.put("errorMsg", "您的车辆已存在待入库的预约，可从我的预约中进行查看");
			return map;
		}

		String oddNumber = ttMaintenanceRecordMapper.maintainOddNumber(maintainDto.getDealerCode());
		TtReservation reservation = new TtReservation();
		reservation.setDealerCode(maintainDto.getDealerCode());
		reservation.setVin(maintainDto.getVin());
		reservation.setReseApplStartTime(maintainDto.getReseApplStartTime());
		if(!CheckUtil.NullOrEmpty(maintainDto.getPhone())){
			reservation.setCustTel(maintainDto.getPhone());
		}
		reservation.setApplyStatus(CodeConstant.MAINTAIN_STATUS_SAVED);
		reservation.setCreateDate(new Date());
		reservation.setSalesConsultantId(maintainDto.getSalesConsultantId().longValue());
		reservation.setAppointType(maintainDto.getAppointType());
		reservation.setSourceType(maintainDto.getSourceType().intValue());
		reservation.setUserId(maintainDto.getUserId());
		reservation.setMaintainname(maintainDto.getMaintainName());
		reservation.setMaintainKm(maintainDto.getMileage());
		reservation.setRemarks(maintainDto.getRemarks());
		reservation.setOddNumber(oddNumber);
		ttReservationMapper.insertSelective(reservation);
		logger.info("保存养修成功！");
		// 发送短信到服务顾问
		// SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		// String date = sdf.format(sendDto.getReseApplStartTime());
		// String s =
		// SmsHttpClient.sendSms(sendDto.getSalesConsultantPhone(),sendDto.getSalesConsultantName()+"您好，菱悦会中有车主进行养修预约，请及时预约确认。车主姓名："+
		// sendDto.getMaintainName()+"先生/女士，车主电话:"+sendDto.getCustTel()+"，预计到店时间："+date+"。",smsPass,smsKey,SMS_CDKEY,SMS_PASS,SMS_BASEURL);
		// logger.info("返回码————" + s);
		map.put("errorCode", "1");
		map.put("data", oddNumber);
		map.put("errorMsg", "预约成功！");
		return map;
	}

	/**
	 * 查询车辆的预约记录
	 * 
	 * @return
	 */
	public int countCarReservations(MaintainDto maintainDto) {
		logger.info("查询车辆有效预约的次数===============");
		Example example = new Example(TtReservation.class);
		Criteria criteria = example.createCriteria();
		criteria.andCondition("vin=", maintainDto.getVin());
		criteria.andCondition("sysdate <", maintainDto.getReseApplStartTime());
		criteria.andIn("applyStatus", Arrays.asList(
				new Object[] { CodeConstant.MAINTAIN_STATUS_SAVED, CodeConstant.MAINTAIN_STATUS_WAIT_MAINTAIN }));
		return ttReservationMapper.selectCountByExample(example);
	}

	/**
	 * @author QianKun 养修预约列表查询
	 * @date 2016年11月17日
	 * @param userId
	 * @return
	 */
	public List<MaintainDto> getMaintainData(String openId) {
		List<MaintainDto> dtoList = new ArrayList<>();
		dtoList = ttMaintenanceRecordMapper.queryMaintainData(openId);
		return dtoList;
	}

	/**
	 * @author QianKun 养修预约详情查询
	 * @date 2016年11月17日
	 * @param resnId
	 * @return
	 */
	public List<MaintainDto> getMaintainDataById(String resnId) {
		List<MaintainDto> dtoList = new ArrayList<>();
		dtoList = ttMaintenanceRecordMapper.queryMaintainDataById(resnId);
		return dtoList;
	}

	/**
	 * 养修预约经销商，车辆信息查询
	 * 
	 * @author QianKun
	 * @date 2017年2月17日
	 * @param userId
	 * @return
	 */
	public List<MaintainDto> getMaintainSel(String userId) {
		List<MaintainDto> dtoList = ttMaintenanceRecordMapper.queryMaintainSel(Integer.valueOf(userId));
		if (dtoList != null && !dtoList.isEmpty()) {
			for (int i = 0; i < dtoList.size(); i++) {
				String saleDealer = dtoList.get(i).getSaleDealer();
				String dealerCode = dtoList.get(i).getDealerCode();
				if (!CheckUtil.NullOrEmpty(saleDealer) && !CheckUtil.NullOrEmpty(dealerCode)) {
					if (saleDealer.equals(dealerCode)) {
						logger.info("顾问所在销售店和用户所选销售店一致");
					} else {
						logger.info("顾问所在销售店和用户所选销售店不一致");
						dtoList.get(i).setSaleId("");
						dtoList.get(i).setSaleName("");
						dtoList.get(i).setSaleDealer("");
					}
				} else {
					logger.info("顾问所在销售店和用户所选销售店不一致");
					dtoList.get(i).setSaleId("");
					dtoList.get(i).setSaleName("");
					dtoList.get(i).setSaleDealer("");
				}
			}
		}
		return dtoList;
	}

	/**
	 * 全部省/市查询 90011001：省,90011002：市
	 * 
	 * @author QianKun
	 * @date 2017年2月21日
	 * @return
	 */
	public List<MaintainDealerDto> getMaintainDealerMap(String regionType) {
		List<MaintainDealerDto> dtoList = ttMaintenanceRecordMapper.queryMaintainDealerMap(regionType);
		return dtoList;
	}

	/**
	 * 根据省查市
	 * 
	 * @author QianKun
	 * @date 2017年3月1日
	 * @param parentCode
	 * @return
	 */
	public List<MaintainDealerDto> getSelectCityMap(String parentCode) {
		List<MaintainDealerDto> dtoList = ttMaintenanceRecordMapper.querySelectCityMap(parentCode);
		return dtoList;
	}

	/**
	 * 养修搜索经销商城市
	 * 
	 * @author QianKun
	 * @date 2017年2月21日
	 * @return
	 */
	public List<MaintainDealerDto> getSelectCity(String regionName) {
		List<MaintainDealerDto> dtoList = ttMaintenanceRecordMapper.querySelectCity(regionName);
		return dtoList;
	}

	/**
	 * 查询该城市下的经销商
	 * 
	 * @author QianKun
	 * @date 2017年2月21日
	 * @param tmAdministrationId
	 * @return
	 */
	public List<MaintainDealerDto> getMaintainDealer(String regionName, String dealerCode) {
		List<MaintainDealerDto> dtoList = new ArrayList<>();
		dtoList = ttMaintenanceRecordMapper.queryMaintainDealer(regionName);
		for (MaintainDealerDto mtDto : dtoList) {
			String dCode = mtDto.getDealerCode();
			if (dCode.equals(dealerCode)) {
				mtDto.setRemark("首选店");
			}
		}
		return dtoList;
	}

	/**
	 * 查询该城市下的经销商 (养修预约使用)
	 * 
	 * @author
	 * @date 2017年7月10日
	 * @param regionName
	 * @param dealerCode
	 * @return
	 */
	public List<MaintainDealerDto> getMaintainDealers(String regionName, String dealerCode) {
		List<MaintainDealerDto> dtoList = new ArrayList<>();
		dtoList = ttMaintenanceRecordMapper.queryMaintainDealers(regionName);
		for (MaintainDealerDto mtDto : dtoList) {
			String dCode = mtDto.getDealerCode();
			if (dCode.equals(dealerCode)) {
				mtDto.setRemark("首选店");
			}
		}
		return dtoList;
	}

	/**
	 * 搜索某经销商
	 * 
	 * @author QianKun
	 * @date 2017年3月1日
	 * @param regionCode
	 * @param dealerName
	 * @return
	 */
	public List<MaintainDealerDto> getSearchDealer(String dealerName) {
		List<MaintainDealerDto> dtoList = new ArrayList<>();
		dtoList = ttMaintenanceRecordMapper.querySearchDealer(dealerName);
		return dtoList;
	}

	/**
	 * 搜索某经销商 (养修预约使用)
	 * 
	 * @author QianKun
	 * @date 2017年3月1日
	 * @param regionCode
	 * @param dealerName
	 * @return
	 */
	public List<MaintainDealerDto> getSearchDealers(String dealerName) {
		List<MaintainDealerDto> dtoList = new ArrayList<>();
		dtoList = ttMaintenanceRecordMapper.querySearchDealers(dealerName);
		return dtoList;
	}

	/**
	 * 根据微信ID查找出该用户下绑定的车辆信息
	 * 
	 * @author QianKun
	 * @date 2017年3月8日
	 * @param openId
	 * @return
	 */
	public List<CarModelDto> getCarInfoByOpenID(String openId) {

		return ttMaintenanceRecordMapper.getCarInfoByOpenID(openId);

	}

	/**
	 * 养修预约状态更新
	 * 
	 * @author lyq
	 * @date 2018年1月2日
	 * @param main
	 */
	public void updateMaintainStatus(MaintainFrecordDto main) {
		TtReservation re = new TtReservation();
		re.setResnId(main.getResnId().intValue());
		if (!CheckUtil.NullOrEmpty(main.getApplyStatus())) {
			re.setApplyStatus(main.getApplyStatus().intValue());
		}
		if (!CheckUtil.NullOrEmpty(main.getSalesConsultantId())) {
			re.setSalesConsultantId(main.getSalesConsultantId());
		}
		if (!CheckUtil.NullOrEmpty(main.getReserveDate())) {
			re.setReseApplStartTime(main.getReserveDate());
		}
		re.setUpdateDate(new Date());
		re.setUpdateBy(main.getUserId());
		ttReservationMapper.updateByPrimaryKeySelective(re);

	}

	/**
	 * 养修确认推送消息
	 * 
	 * @author QianKun
	 * @date 2017年3月24日
	 * @param sendDto
	 * @throws Exception
	 */
	public void maintainSendTemp(MaintainDto sendDto) throws Exception {
		logger.info("养修预约确认——推送消息");
		EventMaintainChangedDTO mtDto = new EventMaintainChangedDTO();
		mtDto.setOpenId(sendDto.getOpenId());
		mtDto.setFirstTitle("养修预约确认结果");
		mtDto.setModelName(sendDto.getModelName());
		if (sendDto.getAppointType() == "0") {
			mtDto.setAppointType("保养");
		} else if (sendDto.getAppointType() == "1") {
			mtDto.setAppointType("活动");
		} else if (sendDto.getAppointType() == "2") {
			mtDto.setAppointType("维修");
		} else {
			mtDto.setAppointType("其他");
		}
		mtDto.setStartTime(sendDto.getReseApplStartTime());
		mtDto.setMaintainMileage(Long.valueOf(sendDto.getMileage()));
		mtDto.setUrl("http://" + domainName + "/wx/views/modules/maintenance.html?ID=" + sendDto.getResnId());
		mtDto.setRemark("");
		mtDto.setTemplateNum(sendDto.getTemplateNum());
		// logger.info("推送消息——" + mtDto);
		BizEvent event = new BizEvent();
		event.setEventBizType(EventBizType.REPAIR_APPOINTMENT);
		event.setEventBizStep(EventBizStep.REPAIR_APPOINTMENT_CONFIRM_INFORM);
		event.setEventKey("");
		event.setEventData(MapConverUtil.PO2Map(mtDto));
		String s = eventService.sendEvent2MQ(event);
		logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);

	}

	/**
	 * 维修预约确认
	 * 
	 * @author QianKun
	 * @date 2017年3月25日
	 * @param maintainDto
	 * @return
	 */
	public ResultMessage applyConfire(@RequestBody IfMessage<List<ApplyConfirm>> info) {

		ResultMessage message = new ResultMessage();
		try {
			// logger.info("接口传来的数据=====" + info);
			// 获取DCMS传来的状态
			Integer Status = info.getIfData().get(0).getStatus();
			String OddNumber = info.getIfData().get(0).getReservationNO();
			String drivingStatus = info.getIfData().get(0).getDrivingStatus();
			String name = info.getIfData().get(0).getName();
			String mobile = info.getIfData().get(0).getMobile();

			// 根据传入的单号去查询该条记录的状态
			// ttMaintenanceRecordMapper.selectMaintainByOdd

			MaintainDto maintainDto = new MaintainDto();
			maintainDto.setOddNumber(OddNumber);
			if (Status.equals(1)) {
				// 状态——成功
				logger.info("状态——成功");
				maintainDto.setApplyStatus((long) 10011002);
				maintainDto.setDrivingStatus(drivingStatus);
				maintainDto.setName(name);
				maintainDto.setMobile(mobile);
				ttMaintenanceRecordMapper.updateAppointment(maintainDto);

				// 发放卡券
				Integer potentialUserId = ttMaintenanceRecordMapper.selectPotentialUserByOdd(OddNumber);
				logger.info("该用户的潜客ID为：" + potentialUserId);
				String dealerCode = ttMaintenanceRecordMapper.selectDealerById(potentialUserId);
				logger.info("自动发放卡券");
				SendTicket ticketDto = new SendTicket();
				ticketDto.setBizCode(1003);
				ticketDto.setTriggerCode(10031001);
				ticketDto.setUserId(potentialUserId);
				ticketDto.setBizId(OddNumber);
				// logger.info("该用户的销售店为："+dealerCode);
				if (dealerCode != null) {
					ticketDto.setDealerCode(dealerCode);
				} else {
					ticketDto.setDealerCode("");
				}
				ticketDto.setBatchId("");
				BizEvent et = new BizEvent();
				et.setEventBizType(EventBizType.SEND_TICKET);
				et.setEventBizStep(EventBizStep.SEND_TICKTE_TO_USER);
				et.setEventKey("TICKET:" + ticketDto.getUserId() + ":" + new Date().getTime());
				et.setEventData(MapConverUtil.PO2Map(ticketDto));
				String s = eventService.sendEvent2MQ(et);
				logger.info("发放卡券MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);

				// 根据单号查出详情
				MaintainDto mtDto = ttMaintenanceRecordMapper.selectMaintainByOdd(maintainDto.getOddNumber());
				// 推送消息模板
				maintainSendTemp(mtDto);
			} else if (Status.equals(2)) {
				// 状态——取消
				logger.info("状态——取消");
				maintainDto.setApplyStatus((long) 10011005);
				ttMaintenanceRecordMapper.updateAppointment(maintainDto);
			} else if (Status.equals(3)) {
				// 状态——改时间
				logger.info("状态——改时间");
				maintainDto.setApplyStatus((long) 10011002);
				ttMaintenanceRecordMapper.updateAppointment(maintainDto);
				// 根据单号查出详情
				MaintainDto mtDto = ttMaintenanceRecordMapper.selectMaintainByOdd(maintainDto.getOddNumber());
				// 推送消息模板
				maintainSendTemp(mtDto);
			} else {
				logger.info("状态失败");
				// 状态失败
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return message;
	}

	/**
	 * 维修工单反馈接口
	 * 
	 * @author Administrator
	 * @date 2017年3月25日
	 * @param info
	 * @return
	 * @throws Exception
	 */
	public ResultMessage maintainInfo(@RequestBody IfMessage<List<MaintainInfo>> info) throws Exception {
		ResultMessage message = new ResultMessage();
		try {
			MaintenanceDto maintenanceDto = new MaintenanceDto();
			maintenanceDto.setDrivingStatus(info.getIfData().get(0).getDrivingStatus());
			maintenanceDto.setServerName(info.getIfData().get(0).getServerName());
			maintenanceDto.setMobile(info.getIfData().get(0).getMobile());
			maintenanceDto.setVin(info.getIfData().get(0).getVin());
			maintenanceDto.setReservationNo(info.getIfData().get(0).getReservationNO());
			maintenanceDto.setDealerCode(info.getIfData().get(0).getAfterSalesCode());
			maintenanceDto.setMaintenanceWorkOrderNum(info.getIfData().get(0).getWorkOrderNo());
			maintenanceDto.setMileage((long) info.getIfData().get(0).getCurMileage());
			;
			maintenanceDto.setExpectedTime(info.getIfData().get(0).getExpectedTime());

			if (maintenanceDto.getExpectedTime() != null && !"".equals(maintenanceDto.getExpectedTime())) {
				maintenanceDto.setExpectedTimeDate(
						DateUtil.parseDate(maintenanceDto.getExpectedTime(), "yyyy-MM-dd HH:mm:ss"));
			}

			maintenanceDto.setDeliveryTime(info.getIfData().get(0).getDeliveryTime());

			if (maintenanceDto.getDeliveryTime() != null && !"".equals(maintenanceDto.getDeliveryTime())) {
				maintenanceDto.setDeliveryTimeDate(
						DateUtil.parseDate(maintenanceDto.getDeliveryTime(), "yyyy-MM-dd HH:mm:ss"));
			}

			maintenanceDto.setProjectInfo(info.getIfData().get(0).getProjectInfo());
			maintenanceDto.setPartInfo(info.getIfData().get(0).getPartInfo());
			maintenanceDto.setRemark(info.getIfData().get(0).getSuggestion());
			maintenanceDto.setSaName(info.getIfData().get(0).getName());
			maintenanceDto.setMaintenanceWorkOrderType(info.getIfData().get(0).getMaintenanceStatus());
			MaintainDto maintainDto = new MaintainDto();
			maintainDto.setOddNumber(info.getIfData().get(0).getReservationNO());
			// 查询是否存在该车
			String carId = ttMaintenanceRecordMapper.selectCar(maintenanceDto.getVin());

			if (carId != null && !"".equals(carId)) {
				Integer carIdInt = Integer.valueOf(carId);
				Integer userId = ttMaintenanceRecordMapper.getUserId(carIdInt);
				logger.info("存在该车！");
				// 查询该维修工单
				List<MaintenanceDto> mtOrderDtp = ttMaintenanceRecordMapper.queryMaintenanceByIdMap(
						info.getIfData().get(0).getWorkOrderNo(), maintenanceDto.getDealerCode());
				if (mtOrderDtp == null || mtOrderDtp.isEmpty()) {
					// 没有该工单，插入一条
					ttMaintenanceRecordMapper.insertMaintenanceOrder(maintenanceDto);
					// 判断有没有传入预约单号
					if (info.getIfData().get(0).getReservationNO() != null
							&& !"".equals(info.getIfData().get(0).getReservationNO())) {
						// 查询是否存在该养修单
						MaintainDto mtDto = ttMaintenanceRecordMapper.selectMaintainByOdd(maintainDto.getOddNumber());
						if (mtDto != null) {
							// 有预约单号，更新该养修预约的预约时间
							ttMaintenanceRecordMapper.updateMaintainTime(maintainDto);
							// 发送养修预约到达事件
							EventRepairAppointmentArrivedDTO repairAppointmentArrivedDTO = new EventRepairAppointmentArrivedDTO();
							repairAppointmentArrivedDTO.setAppointmentNo(mtDto.getOddNumber());
							repairAppointmentArrivedDTO.setPhone(mtDto.getCustTel());
							repairAppointmentArrivedDTO.setUserId(Integer.parseInt(mtDto.getUserId()));
							BizEvent event = new BizEvent();
							event.setEventBizType(EventBizType.REPAIR_APPOINTMENT);
							event.setEventBizStep(EventBizStep.REPAIR_APPOINTMENT_ARRIVED);
							event.setEventKey("WXGD" + "-" + repairAppointmentArrivedDTO.getAppointmentNo());
							event.setEventData(MapConverUtil.PO2Map(repairAppointmentArrivedDTO));
							String s = eventService.sendEvent2MQ(event);
							logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
						}
					}
				} else {
					// 已有该工单，更新一条
					ttMaintenanceRecordMapper.updateMaintenanceOrder(maintenanceDto);
					/*
					 * String oddNo=info.getIfData().get(0).getReservationNO();
					 * Integer
					 * oddNoCount=ttMaintenanceRecordMapper.queryOddNoCount(
					 * oddNo); if(oddNoCount==0||oddNo==null){
					 * logger.info("预约单号："+oddNo+"+不存在预约表里，不生成评价"); }
					 */
					// logger.info("判断生成评价的工单号："+maintenanceDto.getMaintenanceWorkOrderNum());
					logger.info("判断生成评价的经销商代码：" + maintenanceDto.getDealerCode());
					Integer oddNoCount = ttMaintenanceRecordMapper.selectOddNoCount(maintenanceDto);
					logger.info("获得的预约单号数量：" + oddNoCount);
					if (userId != null) {
						logger.info("评价工单发起MQ事件！");
						EventEvaluationDTO eventEvaluationDTO = new EventEvaluationDTO();
						eventEvaluationDTO.setType(1);
						eventEvaluationDTO.setOrderNumber(
								maintenanceDto.getMaintenanceWorkOrderNum() + maintenanceDto.getDealerCode());
						logger.info("接收的工单号：" + maintenanceDto.getMaintenanceWorkOrderNum()
								+ maintenanceDto.getDealerCode());
						eventEvaluationDTO.setUserId(userId);
						logger.info("接收的userId:" + userId);
						BizEvent event = new BizEvent();
						event.setEventBizType(EventBizType.REPAIR_ORDER);
						event.setEventBizStep(EventBizStep.REPAIR_ORDER_EVALUATED_SEND);
						event.setEventKey("EVALUA" + "-" + eventEvaluationDTO.getOrderNumber() + "-"
								+ maintenanceDto.getDealerCode());
						logger.info("签名：" + event.getEventKey());
						event.setEventData(MapConverUtil.PO2Map(eventEvaluationDTO));
						String s = eventService.sendEvent2MQ(event);
						logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
					} else {
						logger.info("userId和oddNoCount:为空！");
					}
				}

			}

		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
		return message;
	}

	/**
	 * 养修预约信息发送
	 * 
	 * @author QianKun
	 * @date 2017年3月25日
	 * @param maintainDto
	 * @throws Exception
	 */
	public void maintainSend(@RequestBody MaintainDto maintainDto) throws Exception {
		logger.info("MaintainSend——Start");
		IfMessage<List<EventMaintainSendMessageDto>> l = new IfMessage<>();
		List<EventMaintainSendMessageDto> list = new ArrayList<>();
		EventMaintainSendMessageDto mtSend = new EventMaintainSendMessageDto();

		mtSend.setArrivalTime(DateUtil.formateDate(maintainDto.getReseApplStartTime(), "yyyy-MM-dd HH:mm:ss"));
		if (maintainDto.getMileage() == null || maintainDto.getMileage().isEmpty()) {
			mtSend.setCurMileage(" ");
		} else {
			mtSend.setCurMileage(maintainDto.getMileage());
		}
		// logger.info("Mileage:" + mtSend.getCurMileage());
		if (maintainDto.getDealerCode() == null || maintainDto.getDealerCode().isEmpty()) {
			mtSend.setDealerCode(" ");
		} else {
			mtSend.setDealerCode(maintainDto.getDealerCode());
		}
		// logger.info("DealerCode:" + mtSend.getDealerCode());
		if (maintainDto.getRemarks() == null || maintainDto.getRemarks().isEmpty()) {
			mtSend.setMemo(" ");
		} else {
			mtSend.setMemo(maintainDto.getRemarks());
		}
		mtSend.setMobileNO(maintainDto.getCustTel());
		// logger.info("MobileNo:" + mtSend.getMobileNO());
		if (maintainDto.getSalesConsultantId() == null) {
			mtSend.setName(" ");
		} else {
			mtSend.setName(maintainDto.getSalesConsultantId().toString());
		}
		// logger.info("Memo为：" + mtSend.getMemo());
		if (maintainDto.getSalesConsultantId() != null) {
			mtSend.setName(maintainDto.getSalesConsultantId().toString());
		} else {
			mtSend.setName("");
		}
		mtSend.setReservationNO(maintainDto.getOddNumber());
		mtSend.setReservationType(maintainDto.getAppointType());
		mtSend.setStatus((long) 0);
		mtSend.setCustName(maintainDto.getMaintainName());
		// logger.info("CustName为：" + mtSend.getCustName());
		mtSend.setVin(maintainDto.getVin());
		// logger.info("mtSend为：" + mtSend);
		list.add(mtSend);
		l.setIfData(list);
		// logger.info("Mileage为：" + list.get(0).getCurMileage());
		// logger.info("MobileNO为：" + list.get(0).getMobileNO());
		// logger.info("CustName为：" + list.get(0).getCustName());
		// logger.info("Memo为：" + list.get(0).getMemo());
		String time = String.valueOf(new Date().getTime());
		String transferNo = MD5Util.MD5("IC001" + time + CommonConstant.HTTP_CLUB_KEY);

		l.setIfCode("IC001");
		l.setOccurtime(time);
		l.setTransferNo(transferNo);
		l.setDataCnt(1);
		String data = JSON.toJSONString(l).toString();
		logger.info("SendToMQ,data=" + data);
		String s = eventService.sendMessage2MQ(MQChannelType.appAppointmentInfo, data);
		logger.info("MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
		logger.info("SendEnd");
	}

	public List<Map<String, Object>> workStations(List<String> list, String dealerCode, String time) throws Exception {
		List<Map<String, Object>> re = new ArrayList<>();
		List<WorkStationsDto> resultList = new ArrayList<>();
		try {
			String uri = MaintainConstant.DMS_TIME_URL;
			ArrayList<String> strArray = new ArrayList<>();
			List<Map<String, Object>> li = new ArrayList<>();
			for (int i = 0; i < list.size(); i++) {
				String date = list.get(i);
				logger.info("时间为>>>>>>>" + date);
				Map<String, Object> map = new HashMap<>();
				map.put("afterSalesCode", dealerCode);
				map.put("orderTime", time + " " + date);
				li.add(map);
			}
			logger.info("Array>>>>>>" + strArray);
			resultList = HttpCommonUtil.getOwnerInfos(li, "IC014", uri, WorkStationsDto.class);
			for (int i = 0; i < resultList.size(); i++) {
				Map<String, Object> result = new HashMap<>();
				result.put("orderTime", resultList.get(i).getOrderTime());
				result.put("workstations", resultList.get(i).getPositionCount());
				re.add(result);
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			for (int i = 0; i < list.size(); i++) {
				Map<String, Object> result = new HashMap<>();
				result.put("orderTime", time + " " + list.get(i));
				result.put("workstations", "");
				re.add(result);
			}
		}
		return re;
	}

	public Map<String, Object> insuranceExpireInfo() {
		Map<String, Object> resultMap = new HashMap<>();
		Date insuranceDate = new Date();
		String memo = "";
		String vin = "";
		Map<String, Object> param = new HashMap<String, Object>();
		String url = insuranceUrl;
		try {
			// 调用DCMS接口
			List<InsuranceDto> resultDto = HttpCommonUtil.getOwnerInfo(param, "IC018", url, InsuranceDto.class);
			if (resultDto.size() == 0) {
				logger.info("DCMS返回数据为空");
			} else {
				logger.info("有返回数据，将数据落地");
				int b = 0;
				for (int a = 0; a < resultDto.size(); a++) {
					insuranceDate = resultDto.get(a).getInsuranceDate();
					memo = ttMaintenanceRecordMapper.selectInsuranCode(resultDto.get(a).getMemo());
					vin = resultDto.get(a).getVin();
					logger.info("将数据落地");
					Example ex = new Example(TmCarInfo.class);
					ex.createCriteria().andCondition("VIN=", vin);
					TmCarInfo record = new TmCarInfo();
					record.setVin(vin);
					if (memo != null) {
						record.setInsurer(memo);
					} else {
						record.setInsurer("");
					}
					record.setInsuranceEndDate(insuranceDate);
					b = b + tmCarInfoMapper.updateByExampleSelective(record, ex);
				}
				logger.info("更新了" + b + "条");
			}
			resultMap.put("result", "200");
			resultMap.put("resultMsg", "更新保险到期数据成功！");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			resultMap.put("result", "500");
			resultMap.put("resultMsg", "更新保险到期数据失败！");
		}
		return resultMap;
	}

	public Map<String, Object> insuranceExpire() {
		Map<String, Object> resultMap = new HashMap<String, Object>();
		try {
			List<InsuranceExpireDto> list = ttMaintenanceRecordMapper.selectInsuranceExpire(insuranceDate);
			if (list.size() == 0) {
				logger.info("没有需要推送保险到期的人");
				resultMap.put("result", "200");
				resultMap.put("resultMsg", "暂无符合推送条件的数据");
			} else {
				Map<String, Object> map = new HashMap<String, Object>();
				for (int i = 0; i < list.size(); i++) {
					SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
					Date date = list.get(i).getInsuranceEndDate();
					String INSURANCEENDDATE = sdf.format(date);
					map.put("INSURANCEENDDATE", INSURANCEENDDATE);
					// map.put("INSURANCESTARTDATE",
					// list.get(i).getInsuranceStartDate());
					map.put("OPENID", list.get(i).getOpenId());
					SendInsuranceExpire(map);
				}
				resultMap.put("result", "200");
				resultMap.put("resultMsg", "推送保险到期提醒成功！");
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			resultMap.put("result", "500");
			resultMap.put("resultMsg", "推送保险到期提醒失败！");
		}
		return resultMap;
	}

	public Map<String, Object> maintainExpire() {
		Map<String, Object> resultMap = new HashMap<>();
		String maintenanceDate = "";
		String memo = "";
		String vin = "";
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		Map<String, Object> param = new HashMap<String, Object>();
		String url = maintainUrl;
		try {
			// 调用DCMS接口
			List<MaintainExpireDto> resultDto = HttpCommonUtil.getOwnerInfo(param, "IC017", url,
					MaintainExpireDto.class);
			if (resultDto.size() == 0) {
				logger.info("DCMS返回数据为空");
			} else {
				for (int a = 0; a < resultDto.size(); a++) {
					maintenanceDate = sdf.format(resultDto.get(a).getMaintenanceDate());
					memo = resultDto.get(a).getMemo();
					vin = resultDto.get(a).getVin();
					Map<String, Object> map = new HashMap<String, Object>();
					logger.info("根据车辆VIN码搜索对应信息");
					map = ttMaintenanceRecordMapper.selectMaintainExpireInfo(vin);
					map.put("MEMO", memo);
					logger.info("将保养到期消息推送给对应的人");
					map.put("expireDate", maintenanceDate);
					SendMaintainExpire(map);
				}
			}
			resultMap.put("result", "200");
			resultMap.put("resultMsg", "保养到期推送成功！");
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			resultMap.put("result", "500");
			resultMap.put("resultMsg", "保养到期推送失败！");
		}
		return resultMap;
	}

	public void SendInsuranceExpire(Map<String, Object> map) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
		logger.info("推送消息模板");
		try {
			Date insuranceEndDate = sdf.parse(map.get("INSURANCEENDDATE").toString());
			logger.info("到期时间：" + insuranceEndDate);
			Date insuranceStartDate = sdf.parse(map.get("INSURANCEENDDATE").toString());
			insuranceStartDate.setYear(insuranceStartDate.getYear() - 1);
			logger.info("时间：" + insuranceStartDate + "——" + insuranceStartDate);
			logger.info("推送保险到期消息模板事件到MQ");
			// 具体业务参数
			EventInsuranceExpireDTO eventDate = new EventInsuranceExpireDTO();
			eventDate.setOpenId(map.get("OPENID").toString());
			eventDate.setInsuranceEndDate(insuranceEndDate);
			eventDate.setInsuranceStartDate(insuranceStartDate);
			// 业务事件
			BizEvent bizEvent = new BizEvent();
			bizEvent.setEventKey("INSURANCE_TEMPLATE:" + new Date().getTime());
			bizEvent.setEventBizType(EventConstant.EventBizType.SEND_TEMPLATE);
			bizEvent.setEventBizStep(EventConstant.EventBizStep.SEND_INSURANCE_TEMPLATE);
			bizEvent.setEventData(MapConverUtil.PO2Map(eventDate));
			// logger.info(bizEvent.toString());
			String returnString = "";
			returnString = eventService.sendEvent2MQ(bizEvent);
			logger.info("推送保险到期消息模板事件到MQ结束:" + returnString);
			logger.info("发送消息通知");
			Integer userId = ttMaintenanceRecordMapper.selectPotentialUser(eventDate.getOpenId());
			MessageDto dto = new MessageDto();
			dto.setMessageContent("您的爱车保险即将到期，建议您尽快续保。到期时间：" + map.get("INSURANCEENDDATE").toString());
			dto.setMessageTitle("保险到期提醒");
			dto.setMessageType("40011005");
			dto.setUserId(userId.longValue());
			BizEvent et = new BizEvent();
			et.setEventBizType(EventBizType.SEND_MESSAGE);
			et.setEventBizStep(EventBizStep.SEND_MESSAGE_NOTICE);
			et.setEventKey("MESSAGE:" + dto.getUserId() + ":" + new Date().getTime());
			et.setEventData(MapConverUtil.PO2Map(dto));
			String s = eventService.sendEvent2MQ(et);
			logger.info("发送消息通知，MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}

	public void SendMaintainExpire(Map<String, Object> map) {
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String d = map.get("expireDate").toString();
			Date expireDate = new Date();
			expireDate = sdf.parse(d);
			String modelType = map.get("MODELTYPE").toString();
			String regionNo = map.get("REGIONNO").toString();
			String userName = map.get("USERNAME").toString();
			String memo = map.get("MEMO").toString();
			logger.info("推送保养到期消息模板事件到MQ");
			// 具体业务参数
			EventMaintainExpireDTO eventDate = new EventMaintainExpireDTO();
			eventDate.setOpenId(map.get("OPENID").toString());
			eventDate.setExpireDate(expireDate);
			eventDate.setModelType(modelType);
			eventDate.setRegionNo(regionNo);
			eventDate.setUserName(userName);
			eventDate.setRemark("保养项目：" + memo);
			// 业务事件
			BizEvent bizEvent = new BizEvent();
			bizEvent.setEventKey("MAINTAIN_TEMPLATE:" + new Date().getTime());
			bizEvent.setEventBizType(EventConstant.EventBizType.SEND_TEMPLATE);
			bizEvent.setEventBizStep(EventConstant.EventBizStep.SEND_MAINTAIN_TEMPLATE);
			bizEvent.setEventData(MapConverUtil.PO2Map(eventDate));
			logger.info(bizEvent.toString());
			String returnString = "";
			returnString = eventService.sendEvent2MQ(bizEvent);
			logger.info("推送保养到期消息模板事件到MQ结束:" + returnString);
			logger.info("发送消息通知");
			Integer userId = ttMaintenanceRecordMapper.selectPotentialUser(eventDate.getOpenId());
			MessageDto dto = new MessageDto();
			dto.setMessageContent("您的车辆保养即将到期，为确保您的出行顺畅，请及时到店保养。到期时间：" + d);
			dto.setMessageTitle("保养到期提醒");
			dto.setMessageType("40011005");
			dto.setUserId(userId.longValue());
			BizEvent et = new BizEvent();
			et.setEventBizType(EventBizType.SEND_MESSAGE);
			et.setEventBizStep(EventBizStep.SEND_MESSAGE_NOTICE);
			et.setEventKey("MESSAGE:" + dto.getUserId() + ":" + new Date().getTime());
			et.setEventData(MapConverUtil.PO2Map(dto));
			String s = eventService.sendEvent2MQ(et);
			logger.info("发送消息通知，MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
	}
}
